const jwt = require("jsonwebtoken");
const User = require("../models/User");

async function authMiddleware(req, res, next) {
  try {
    const header = req.headers["authorization"] || "";
    const [scheme, token] = header.split(" ");
    if (scheme !== "Bearer" || !token) {
      return res.status(401).json({ message: "未提供有效的 Authorization 头" });
    }

    const accessSecret =
      process.env.ACCESS_TOKEN_SECRET ||
      process.env.JWT_SECRET ||
      "dev_access_secret";
    const payload = jwt.verify(token, accessSecret);
    const userId = payload && payload.sub;
    if (!userId) {
      return res.status(401).json({ message: "无效的令牌" });
    }

    const user = await User.findById(userId).lean();
    if (!user) {
      return res.status(401).json({ message: "用户不存在或已被删除" });
    }

    // 校验 tokenVersion 一致
    if ((payload && payload.ver) !== (user.tokenVersion || 0)) {
      return res.status(401).json({ message: "令牌已失效" });
    }

    req.user = { id: user._id, email: user.email, username: user.username };
    return next();
  } catch (err) {
    console.error(err);
    return res.status(401).json({ message: "鉴权失败" });
  }
}

module.exports = authMiddleware;
